package com.tz.crm.dao.impl;

import com.tz.crm.dao.UserDao;
import com.tz.crm.dao.VisitRecordDao;
import com.tz.crm.entity.Role;
import com.tz.crm.entity.User;
import com.tz.crm.entity.VisitRecord;
import com.tz.crm.entity.VisitType;
import com.tz.crm.entity.dto.Report;
import com.tz.crm.utils.DayCalculateUtil;
import org.hibernate.Hibernate;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 使用 @Repository 将 DAO 类声明为 Bean
 */
@SuppressWarnings("JpaQlInspection")
@Repository
@Transactional
public class VisitRecordDaoImpl extends BaseDaoImpl<VisitRecord, String>
        implements VisitRecordDao {

    @Autowired
    private UserDao userDao;

    @Override
    public List<Report> report(List<User> ownerList,
                               List<VisitType> visitTypeList, Date fromDate, Date toDate,
                               Boolean onlyWorkDays, User user) {
        String hql = "where 1=1 ";
        if (visitTypeList != null && visitTypeList.size() != 0) {
            hql += "and visitType in :vtList ";
        }
        if (ownerList != null && ownerList.size() != 0) {
            hql += "and owner in (:ownerList) ";
        } else {
            int flag = 0;
            Hibernate.initialize(user.getRoleSet());
            for (Role r : user.getRoleSet()) {
                if ("admin".equals(r.getValue())
                        || "salesManager".equals(r.getValue())) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) {
                ownerList = userDao.getList("dept", user.getDept());
                hql += "and owner in (:ownerList) ";
            } else {
                user = userDao.get(user.getId());
                hql += "and owner=:ownerList ";
            }
        }
        if (fromDate != null && toDate != null) {
            hql += "and visitDate between :fromDate and :toDate ";
        }
        String hql2 = "select count(owner)from VisitRecord " + hql;
        hql2 += "and firstVisit =true and owner=out.owner";


        String hql3 = "select count(owner),owner.realName,(" + hql2
                + ") from VisitRecord out " + hql + "group by owner,owner.realName";
        Query query = getSession().createQuery(hql3);

        if (visitTypeList != null && visitTypeList.size() != 0) {
            query.setParameterList("vtList", visitTypeList);
        }
        if (ownerList != null && ownerList.size() != 0) {
            query.setParameterList("ownerList", ownerList);
        } else {
            int flag = 0;
            for (Role r : user.getRoleSet()) {
                if ("admin".equals(r.getValue())
                        || "salesManager".equals(r.getValue())) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) {
                ownerList = userDao.getList("dept", user.getDept());
                query.setParameterList("ownerList", ownerList);
            } else {
                user = userDao.get(user.getId());
                query.setParameter("ownerList", user);
            }
        }
        if (fromDate != null && toDate != null) {
            query.setParameter("fromDate", fromDate);
            query.setParameter("toDate", toDate);
        }

        List<Report> reports = new ArrayList<Report>();
        for (Object obj : query.list()) {
            Object[] objs = (Object[]) obj;
            Report report = new Report();
            if (onlyWorkDays) {
                report.setCountDay(DayCalculateUtil.countWorkDays(fromDate,
                        toDate));
            } else {
                report.setCountDay(DayCalculateUtil.countDays(fromDate,
                        toDate));
            }
            report.setUserName((String) objs[1]);
            report.setCountVisit(Integer.parseInt(objs[0].toString()));
            report.setNewCustomerVisit(Integer.parseInt(objs[2].toString()));
            reports.add(report);
        }
        return reports;
    }

    /**
     * 根据客户id 获取其拜访记录
     *
     * @param id
     */
    @Override
    public List<VisitRecord> getAllByCusId(String id) {
        return getSession().createQuery("from VisitRecord where customer.id=?").setParameter(0,id).list();
    }

    @Override
    public int getCount(int awayMonth) {
        String hql = "select count(owner) from VisitRecord where visitDate between :myFromDate and :myToDate";
        Calendar firstDay = Calendar.getInstance();
        Calendar lastDay = Calendar.getInstance();
        firstDay.set(firstDay.get(Calendar.YEAR), firstDay.get(Calendar.MONTH) - awayMonth, 1);
        lastDay.set(lastDay.get(Calendar.YEAR), lastDay.get(Calendar.MONTH) - awayMonth + 1, 0);
        Query query = getSession().createQuery(hql);
        query.setParameter("myFromDate", firstDay.getTime());
        query.setParameter("myToDate", lastDay.getTime());
        return Integer.parseInt(query.uniqueResult().toString());
    }

    @Override
    public int getTotalCountByCustomerId(String customerId) {
        String hql = "select count(v.firstVisit) from VisitRecord v " +
                "where v.customer.id = :id";
        Query query = getSession().createQuery(hql)
                .setParameter("id",customerId);
        return Integer.parseInt(query.uniqueResult().toString());
    }
}
